package com.umakr.ax.wechat.util;

import com.google.gson.Gson;
import com.umakr.ax.wechat.vo.WeixinOpenAccountEntity;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
 * @author wangmingdong
 */
public class SpeedStorage {
    public static Map<String, String> DATA = new HashMap<>();
    public static File speedStorageFile = new File("SpeedStorage");
    public static Gson gson = new Gson();
    public static Date getSystemDate() {
        return new Date(System.currentTimeMillis());
    }

    static {
        getFile();
    }

    public static <T> T load(String key, Class<T> tClass) {
        String value = DATA.get(key);
        try {
            if (value == null) {
                String json = FileUtils.readFileToString(getFile());
                if (json != null && !"".equals(json.trim())) {
                    Map<String, String> data = gson.fromJson(json, Map.class);
                    DATA.putAll(data);
                    value = DATA.get(key);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return gson.fromJson(value, tClass);
    }

    public static void save(String key, Object value) {
        try {
            System.out.println("SpeedStorage Before :" + gson.toJson(DATA) + ";" + load(key, Object.class));
            DATA.put(key, gson.toJson(value));

            String json = FileUtils.readFileToString(getFile());
            if (json != null && !"".equals(json.trim())) {
                Map<String, String> data = gson.fromJson(json, Map.class);
                data.putAll(DATA);
                DATA = data;
            }

            FileUtils.writeStringToFile(getFile(), gson.toJson(DATA));
            System.out.println("SpeedStorage After :" + gson.toJson(DATA) + ";" + load(key, Object.class));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File getFile() {
        try {
            if (!speedStorageFile.exists()) {
                System.out.println("极简存储.分配存储空间.........  wmdz  2018/01/06");
                speedStorageFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return speedStorageFile;
    }

    public static void main(String[] args) {
        WeixinOpenAccountEntity entity = new WeixinOpenAccountEntity();
        entity.setAppid("123");
        entity.setTicket("456");
        entity.setId("789");
        SpeedStorage.save("WeixinOpenAccountEntity" + "123", entity);
        WeixinOpenAccountEntity loadData = SpeedStorage.load("WeixinOpenAccountEntity" + "123", WeixinOpenAccountEntity.class);
        System.out.println("测试完成:" + loadData.getTicket());
    }
}
